import cv2
import matplotlib.pyplot as plt
import numpy as np

img = cv2.imread('img/example.png')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 二进制阈值法
ret, binary = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
# 反二进制阈值法
ret, binary_inv = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
# 截断阈值法
ret, trunc = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC)
# 超阈值为0法
ret, tozero = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO)
# 反超阈值为0法
ret, tozero_inv = cv2.threshold(img_gray, 127, 127, cv2.THRESH_TOZERO_INV)

title = ['gray', 'binary', 'binary_inv', 'trunc', 'tozero', 'tozero_inv']
imgs = [img_gray, binary, binary_inv, trunc, tozero, tozero_inv]
for i in range(6):
    plt.subplot(2, 3, i+1)
    plt.imshow(imgs[i], cmap='gray')
    plt.title(title[i])
    plt.axis('off')
plt.show()